import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/setting/models/version_entity.dart';
import 'package:flutter_deer/setting/provider/app_update_provider.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/util/version_utils.dart';
import 'package:flutter_deer/widgets/my_button.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';


class UpdateDialog extends StatefulWidget {

  const UpdateDialog({super.key,this.versionEntity});

  final VersionEntity? versionEntity;

  @override
  _UpdateDialogState createState() => _UpdateDialogState();
}

class _UpdateDialogState extends State<UpdateDialog> {
  
  final CancelToken _cancelToken = CancelToken();
  bool _isDownload = false;
  AppUpdateProvider provider = AppUpdateProvider();

  
  @override
  void dispose() {
    if (!_cancelToken.isCancelled && provider.downloadValue != 1) {
      _cancelToken.cancel();
    }
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    final Color primaryColor = Theme.of(context).primaryColor;
    List<String>? contents = widget.versionEntity!.contents;
    return ChangeNotifierProvider<AppUpdateProvider>(
        create: (_) => provider,
        child: Consumer<AppUpdateProvider>(
            builder: (_,provider,child) {
              List<Widget> texts = [];
              texts.add(Text('${DeerLocalizations.of(context)!.newVersionUpdate.nullSafe}', style: TextStyles.textSize16));
              texts.add(Gaps.vGap10);
              for(int i=0;i<contents!.length;i++){
                texts.add(Text(contents.elementAt(i)));
              }
              texts.add(Gaps.vGap15);
              if (_isDownload) {
                texts.add(LinearProgressIndicator(
                  backgroundColor: Colours.line,
                  valueColor: AlwaysStoppedAnimation<Color>(primaryColor),
                  value: provider.downloadValue,
                ));
              }else{
                texts.add(_buildButton(context,provider));
              }
              return WillPopScope(
                onWillPop: () async {
                  /// 使用false禁止返回键返回，达到强制升级目的
                  return true;
                },
                child: Scaffold(
                    resizeToAvoidBottomInset: false,
                    backgroundColor: Colors.transparent,
                    body: Center(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          Container(
                            height: 120.0,
                            width: MediaQuery.of(context).size.width-30,
                            decoration: BoxDecoration(
                              borderRadius: const BorderRadius.only(topLeft: Radius.circular(8.0), topRight: Radius.circular(8.0)),
                              image: DecorationImage(
                                image: ImageUtils.getAssetImage('update_head', format: ImageFormat.jpg),
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width-30,
                            decoration: BoxDecoration(
                                color: context.dialogBackgroundColor,
                                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(8.0), bottomRight: Radius.circular(8.0))
                            ),
                            padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: texts,
                            ),
                          ),

                        ],
                      ),
                    )
                ),
              );
            }
        ));
  }

  Widget _buildButton(BuildContext context,AppUpdateProvider provider) {
    final Color primaryColor = Theme.of(context).primaryColor;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        SizedBox(
          width: MediaQuery.of(context).size.width/3,
          height: 36.0,
          child: MyButton(
            text: '${DeerLocalizations.of(context)!.refuse.nullSafe}',
            fontSize: Dimens.font_sp16,
            textColor: primaryColor,
            disabledTextColor: Colors.white,
            disabledBackgroundColor: Colours.text_gray_c,
            radius: 18.0,
            side: BorderSide(
              color: primaryColor,
              width: 0.8,
            ),
            backgroundColor: Colors.transparent,
            onPressed: () {
              NavigatorUtils.goBack(context);
            },
          ),
        ),
        SizedBox(
          width: MediaQuery.of(context).size.width/3,
          height: 36.0,
          child: MyButton(
            text: '${DeerLocalizations.of(context)!.updateNow.nullSafe}',
            fontSize: Dimens.font_sp16,
            onPressed: () async {
              if (defaultTargetPlatform == TargetPlatform.iOS) {
                NavigatorUtils.goBack(context);
                VersionUtils.jumpAppStore();
              } else {
                setState(() {
                  _isDownload = true;
                });
                _download(provider);
              }
            },
            textColor: context.isDark?Colours.dark_text:Colours.text,
            backgroundColor: primaryColor,
            disabledTextColor: context.isDark?Colours.dark_text:Colours.text,
            disabledBackgroundColor: Colours.text_gray_c,
            radius: 18.0,
          ),
        )
      ],
    );
  }

  ///下载apk
  Future<void> _download(AppUpdateProvider provider) async {
    try {
      setInitDir(initStorageDir: true);
      await DirectoryUtil.getInstance();
      DirectoryUtil.createStorageDirSync(category: 'Download');
      final String path = DirectoryUtil.getStoragePath(fileName: 'deer', category: 'Download', format: 'apk').nullSafe;
      final File file = File(path);
      provider.setDownloadProcess(0.0);
      int totalSize = widget!.versionEntity!.fileSize!;
      await Dio().download(Constant.appUpdateHost+'${widget.versionEntity!.downloadUrl.nullSafe}', path, onReceiveProgress: (count, total) {
        double? value = count / totalSize;
        if (provider.downloadValue != value) {
          if (provider.downloadValue! < 1.0) {
            provider.setDownloadProcess(count / totalSize);
          } else {
            provider.setDownloadProcess(0.0);
          }
        }
      },);
      final res = await InstallPlugin.install(path);

    } catch (e) {
      Toast.show('${DeerLocalizations.of(context)!.downloadFail.nullSafe}');
      setState(() {
        _isDownload = false;
      });
    }
  }
}
